package com.xiaotao.service.impl;

import com.nimbusds.jose.JOSEException;
import com.xiaotao.entity.Admin;
import com.xiaotao.entity.Merchant;
import com.xiaotao.mapper.AdminMapper;
import com.xiaotao.service.AdminService;
import com.xiaotao.util.JwtUtil;
import com.xiaotao.util.ResponseEnum;
import com.xiaotao.util.ResponseUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl implements AdminService {
    @Resource
    private AdminMapper adminMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public ResponseUtil login(Admin admin) throws JOSEException {
        if (admin.getUsername().isEmpty()||admin.getPassword().isEmpty()){
            return ResponseUtil.get(ResponseEnum.FAIL,"商户用户密码不能为空");
        }
        //根据用户名查询密码
        Admin admin1 = adminMapper.findByUsername(admin.getUsername());
        if (!admin.getPassword().equals(admin1.getPassword())){
            //密码错误
            return ResponseUtil.get(ResponseEnum.FAIL,"密码或者用户名错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("admin1", admin1);
        map.put("id", admin1.getId());
        String token = JwtUtil.getToken(map);
        //修改token,有问题前台小程序和后台用户id相同会出问题
        stringRedisTemplate.opsForValue().set("token" + admin1.getId(), token, 3, TimeUnit.HOURS);
        return ResponseUtil.get(ResponseEnum.OK, token);
    }
}
